package cn.t.service.common;

import cn.t.constants.SystemProperties;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component("defaultUploadService")
@AllArgsConstructor
public class DefaultUploadService implements IUploadService {

    private final SystemProperties systemProperties;

    @Override
    public String upload(MultipartFile sourceFile) {

        String filePath = "";
        if (!sourceFile.isEmpty()) {
            try {
                String filename = sourceFile.getOriginalFilename();
                // 之所以保存到 resources 和 target 两个目录，兼顾开发测试和永久保存
                // 只保存到resources目录下每次上传了要重新编译下，target则清理打包后就没有了
                List<File> files = getUploadDirectory();
                // 注意这里一个文件不能循环同时写入多个目录，保存了第一个，第二个要复制过去
                assert filename != null;
                File curFile = new File(files.get(0), filename);
                sourceFile.transferTo(curFile);
                FileCopyUtils.copy(curFile, new File(files.get(1), filename));

                filePath = systemProperties.getUploadPath() + filename;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return filePath;
    }

    /**
     * 获取文件保存路径
     */
    private List<File> getUploadDirectory() throws FileNotFoundException {
        File targetPath = new File(ResourceUtils.getURL("classpath:").getPath());
        if (!targetPath.exists()) {
            // 获取当前运行目录
            targetPath = new File("");
        }
        // 开发环境 resources 目录：可永久保存
        String resourcesPath = System.getProperty("user.dir") + "/web/src/main/resources";
        File path = new File(resourcesPath);
        File upload = new File(path.getAbsolutePath(), "upload");
        File uploadTarget = new File(targetPath.getAbsolutePath(), "upload");
        // 不存在则创建
        List<File> files = new ArrayList<>();
        if (!upload.exists() && upload.mkdirs()) {
            log.info("新建resource上传目录成功");
        }
        if (!uploadTarget.exists() && uploadTarget.mkdirs()) {
            log.info("新建classpath上传目录成功");
        }
        files.add(upload);
        files.add(uploadTarget);
        return files;
    }
}
